home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / pcl / docs.lha / cmu-user / cmu-user.info-5 < prev    next >
Text File  |  1992-08-05  |  53KB  |  1,453 lines

  1. Info file: cmu-user.info,    -*-Text-*-
  2. produced by latexinfo-format-buffer
  3. from file: cmu-user.tex
  4.  
  5.  
  6. 
  7. File: cmu-user.info  Node: Global Function Type Inference, Prev: Local Function Type Inference, Up: Type Inference, Next: Operation Specific Type Inference
  8.  
  9. Global Function Type Inference
  10. ------------------------------
  11.  
  12.  
  13. As described in section *Note Function Types::, a global function type
  14. (ftype) declaration places implicit type assertions on the call
  15. arguments, and also guarantees the type of the return value.  So
  16. wherever a call to a declared function appears, there is no doubt as to
  17. the types of the arguments and return value.  Furthermore, Python will
  18. infer a function type from the function's definition if there is no
  19. `ftype' declaration.  Any type declarations on the argument variables
  20. are used as the argument types in the derived function type, and the
  21. compiler's best guess for the result type of the function is used as the
  22. result type in the derived function type.
  23.  
  24. This method of deriving function types from the definition implicitly assumes
  25. that functions won't be redefined at run-time.  Consider this example:
  26.      
  27.      (defun foo-p (x)
  28.        (let ((res (and (consp x) (eq (car x) 'foo))))
  29.          (format t "It is ~:[not ~;~]foo." res)))
  30.      
  31.      (defun frob (it)
  32.        (if (foo-p it)
  33.            (setf (cadr it) 'yow!)
  34.            (1+ it)))
  35.  
  36.  
  37. Presumably, the programmer really meant to return `res' from `foo-p',
  38. but he seems to have forgotten.  When he tries to call do `(frob (list
  39. 'foo nil))', `frob' will flame out when it tries to add to a `cons'.
  40. Realizing his error, he fixes `foo-p' and recompiles it.  But when he
  41. retries his test case, he is baffled because the error is still there.
  42. What happened in this example is that Python proved that the result of
  43. `foo-p' is `null', and then proceeded to optimize away the `setf' in
  44. `frob'.
  45.  
  46. Fortunately, in this example, the error is detected at compile time due
  47. to notes about unreachable code (?.)  Still, some users may not want to
  48. worry about this sort of problem during incremental development, so
  49. there is a variable to control deriving function types.
  50.  
  51.  
  52.  
  53.  -- Variable: *derive-function-types*
  54.      If true (the default), argument and result type information derived
  55.      from compilation of `defun's is used when compiling calls to that
  56.      function.  If false, only information from `ftype' proclamations
  57.      will be used.
  58.  
  59.  
  60. 
  61. File: cmu-user.info  Node: Operation Specific Type Inference, Prev: Global Function Type Inference, Up: Type Inference, Next: Dynamic Type Inference
  62.  
  63. Operation Specific Type Inference
  64. ---------------------------------
  65.  
  66.  
  67. Many of the standard CMU Common Lisp functions have special type inference procedures
  68. that determine the result type as a function of the argument types.  For
  69. example, the result type of `aref' is the array element type.  Here are some
  70. other examples of type inferences:
  71.      
  72.      (logand x #xFF) =>  (unsigned-byte 8)
  73.      
  74.      (+ (the (integer 0 12) x) (the (integer 0 1) y)) =>  (integer 0 13)
  75.      
  76.      (ash (the (unsigned-byte 16) x) -8) =>  (unsigned-byte 8)
  77.  
  78.  
  79. 
  80. File: cmu-user.info  Node: Dynamic Type Inference, Prev: Operation Specific Type Inference, Up: Type Inference, Next: Type Check Optimization
  81.  
  82. Dynamic Type Inference
  83. ----------------------
  84.  
  85.  
  86. Python uses flow analysis to infer types in dynamically typed programs.  For
  87. example:
  88.      
  89.      (ecase x
  90.        (list (length x))
  91.        ...)
  92.  
  93. Here, the compiler knows the argument to `length' is a list, because the
  94. call to `length' is only done when `x' is a list.  The most significant
  95. efficiency effect of inference from assertions is usually in type check
  96. optimization.
  97.  
  98.  
  99. Dynamic type inference has two inputs: explicit conditionals and
  100. implicit or explicit type assertions.  Flow analysis propagates these
  101. constraints on variable type to any code that can be executed only after
  102. passing though the constraint.  Explicit type constraints come from ifs
  103. where the test is either a lexical variable or a function of lexical
  104. variables and constants, where the function is either a type predicate,
  105. a numeric comparison or `eq'.
  106.  
  107. If there is an `eq' (or `eql') test, then the compiler will actually
  108. substitute one argument for the other in the true branch.  For example:
  109.      
  110.      (when (eq x :yow!) (return x))
  111.  
  112. becomes:
  113.      
  114.      (when (eq x :yow!) (return :yow!))
  115.  
  116. This substitution is done when one argument is a constant, or one argument has
  117. better type information than the other.  This transformation reveals
  118. opportunities for constant folding or type-specific optimizations.  If the test
  119. is against a constant, then the compiler can prove that the variable is not
  120. that constant value in the false branch, or `(not (member :yow!))'
  121. in the example above.  This can eliminate redundant tests, for example:
  122.      
  123.      (if (eq x nil)
  124.          ...
  125.          (if x a b))
  126.  
  127. is transformed to this:
  128.      
  129.      (if (eq x nil)
  130.          ...
  131.          a)
  132.  
  133. Variables appearing as `if' tests are interpreted as `(not (eq VAR
  134. nil))' tests.  The compiler also converts `=' into `eql' where possible.
  135. It is difficult to do inference directly on `=' since it does implicit
  136. coercions.
  137.  
  138. When there is an explicit `<' or `>' test on integer variables, the
  139. compiler makes inferences about the ranges the variables can assume in
  140. the true and false branches.  This is mainly useful when it proves that
  141. the values are small enough in magnitude to allow open-coding of
  142. arithmetic operations.  For example, in many uses of `dotimes' with a
  143. `fixnum' repeat count, the compiler proves that fixnum arithmetic can be
  144. used.
  145.  
  146. Implicit type assertions are quite common, especially if you declare function
  147. argument types.  Dynamic inference from implicit type assertions sometimes
  148. helps to disambiguate programs to a useful degree, but is most noticeable when
  149. it detects a dynamic type error.  For example:
  150.      
  151.      (defun foo (x)
  152.        (+ (car x) x))
  153.  
  154. results in this warning:
  155.      
  156.      In: DEFUN FOO
  157.        (+ (CAR X) X)
  158.      ==>
  159.        X Warning: Result is a LIST, not a NUMBER.
  160.  
  161.  
  162. Note that Common Lisp's dynamic type checking semantics make dynamic type
  163. inference useful even in programs that aren't really dynamically typed, for
  164. example:
  165.      
  166.      (+ (car x) (length x))
  167.  
  168. Here, `x' presumably always holds a list, but in the absence of a
  169. declaration the compiler cannot assume `x' is a list simply because
  170. list-specific operations are sometimes done on it.  The compiler must
  171. consider the program to be dynamically typed until it proves otherwise.
  172. Dynamic type inference proves that the argument to `length' is always a
  173. list because the call to `length' is only done after the list-specific
  174. `car' operation.
  175.  
  176.  
  177. 
  178. File: cmu-user.info  Node: Type Check Optimization, Prev: Dynamic Type Inference, Up: Type Inference
  179.  
  180. Type Check Optimization
  181. -----------------------
  182.  
  183.  
  184. Python backs up its support for precise type checking by minimizing the
  185. cost of run-time type checking.  This is done both through type
  186. inference and though optimizations of type checking itself.
  187.  
  188. Type inference often allows the compiler to prove that a value is of the
  189. correct type, and thus no type check is necessary.  For example:
  190.      
  191.      (defstruct foo a b c)
  192.      (defstruct link
  193.        (foo (required-argument) :type foo)
  194.        (next nil :type (or link null)))
  195.      
  196.      (foo-a (link-foo x))
  197.  
  198. Here, there is no need to check that the result of `link-foo' is a `foo',
  199. since it always is.  Even when some type checks are necessary, type inference
  200. can often reduce the number:
  201.      
  202.      (defun test (x)
  203.        (let ((a (foo-a x))
  204.              (b (foo-b x))
  205.              (c (foo-c x)))
  206.          ...))
  207.  
  208. In this example, only one `(foo-p x)' check is needed.  This applies to a
  209. lesser degree in list operations, such as:
  210.      
  211.      (if (eql (car x) 3) (cdr x) y)
  212.  
  213. Here, we only have to check that `x' is a list once.
  214.  
  215. Since Python recognizes explicit type tests, code that explicitly protects
  216. itself against type errors has little introduced overhead due to implicit type
  217. checking.  For example, this loop compiles with no implicit checks checks for
  218. `car' and `cdr':
  219.      
  220.      (defun memq (e l)
  221.        (do ((current l (cdr current)))
  222.            ((atom current) nil)
  223.          (when (eq (car current) e) (return current))))
  224.  
  225.  
  226. Python reduces the cost of checks that must be done through an optimization
  227. called COMPLEMENTING.  A complemented check for TYPE is simply a check
  228. that the value is not of the type `(not TYPE)'.  This is only
  229. interesting when something is known about the actual type, in which case we can
  230. test for the complement of `(and KNOWN-TYPE (not TYPE))', or the
  231. difference between the known type and the assertion.  An example:
  232.      
  233.      (link-foo (link-next x))
  234.  
  235. Here, we change the type check for `link-foo' from a test for `foo' to a
  236. test for:
  237.      
  238.      (not (and (or foo null) (not foo)))
  239.  
  240. or more simply `(not null)'.  This is probably the most important use of
  241. complementing, since the situation is fairly common, and a `null' test
  242. is much cheaper than a structure type test.
  243.  
  244. Here is a more complicated example that illustrates the combination of
  245. complementing with dynamic type inference:
  246.      
  247.      (defun find-a (a x)
  248.        (declare (type (or link null) x))
  249.        (do ((current x (link-next current)))
  250.            ((null current) nil)
  251.          (let ((foo (link-foo current)))
  252.            (when (eq (foo-a foo) a) (return foo)))))
  253.  
  254. This loop can be compiled with no type checks.  The `link' test for
  255. `link-foo' and `link-next' is complemented to `(not null)', and then
  256. deleted because of the explicit `null' test.  As before, no check is
  257. necessary for `foo-a', since the `link-foo' is always a `foo'.  This
  258. sort of situation shows how precise type checking combined with precise
  259. declarations can actually result in reduced type checking.
  260.  
  261.  
  262. 
  263. File: cmu-user.info  Node: Source Optimization, Prev: Type Inference, Up: Advanced Compiler Use and Efficiency Hints, Next: Tail Recursion
  264.  
  265. Source Optimization
  266. ===================
  267.  
  268.  
  269. This section describes source-level transformations that Python does on
  270. programs in an attempt to make them more efficient.  Although source-level
  271. optimizations can make existing programs more efficient, the biggest advantage
  272. of this sort of optimization is that it makes it easier to write efficient
  273. programs.  If a clean, straightforward implementation is can be transformed
  274. into an efficient one, then there is no need for tricky and dangerous hand
  275. optimization. 
  276.  
  277. * Menu:
  278.  
  279. * Let Optimization::            
  280. * Constant Folding::            
  281. * Unused Expression Elimination::  
  282. * Control Optimization::        
  283. * Unreachable Code Deletion::   
  284. * Multiple Values Optimization::  
  285. * Source to Source Transformation::  
  286. * Style Recommendations::       
  287.  
  288.  
  289. 
  290. File: cmu-user.info  Node: Let Optimization, Prev: Source Optimization, Up: Source Optimization, Next: Constant Folding
  291.  
  292. Let Optimization
  293. ----------------
  294.  
  295.  
  296.  The primary optimization of let variables is to delete them when they
  297. are unnecessary.  Whenever the value of a let variable is a constant, a
  298. constant variable or a constant (local or non-notinline) function, the
  299. variable is deleted, and references to the variable are replaced with
  300. references to the constant expression.  This is useful primarily in the
  301. expansion of macros or inline functions, where argument values are often
  302. constant in any given call, but are in general non-constant expressions
  303. that must be bound to preserve order of evaluation.  Let variable
  304. optimization eliminates the need for macros to carefully avoid spurious
  305. bindings, and also makes inline functions just as efficient as macros.
  306.  
  307. A particularly interesting class of constant is a local function.  Substituting
  308. for lexical variables that are bound to a function can substantially improve
  309. the efficiency of functional programming styles, for example:
  310.      
  311.      (let ((a #'(lambda (x) (zow x))))
  312.        (funcall a 3))
  313.  
  314. effectively transforms to:
  315.      
  316.      (zow 3)
  317.  
  318. This transformation is done even when the function is a closure, as in:
  319.      
  320.      (let ((a (let ((y (zug)))
  321.                 #'(lambda (x) (zow x y)))))
  322.        (funcall a 3))
  323.  
  324. becoming:
  325.      
  326.      (zow 3 (zug))
  327.  
  328.  
  329. A constant variable is a lexical variable that is never assigned to, always
  330. keeping its initial value.  Whenever possible, avoid setting lexical variables
  331. -- instead bind a new variable to the new value.  Except for loop variables,
  332. it is almost always possible to avoid setting lexical variables.  This form:
  333.      
  334.      (let ((x (f x)))
  335.        ...)
  336.  
  337. is MORE efficient than this form:
  338.      
  339.      (setq x (f x)) ...
  340.  
  341. Setting variables makes the program more difficult to understand, both
  342. to the compiler and to the programmer.  Python compiles assignments at
  343. least as efficiently as any other Common Lisp compiler, but most let
  344. optimizations are only done on constant variables.
  345.  
  346. Constant variables with only a single use are also optimized away, even
  347. when the initial value is not constant. (7) (*Note Let
  348. Optimization-Footnotes::) For example, this expansion of `incf':
  349.      
  350.      (let ((#:g3 (+ x 1)))
  351.        (setq x #:G3))
  352.  
  353. becomes:
  354.      
  355.      (setq x (+ x 1))
  356.  
  357. The type semantics of this transformation are more important than the
  358. elimination of the variable itself.  Consider what happens when `x' is
  359. declared to be a `fixnum'; after the transformation, the compiler can
  360. compile the addition knowing that the result is a `fixnum', whereas
  361. before the transformation the addition would have to allow for fixnum
  362. overflow.
  363.  
  364. Another variable optimization deletes any variable that is never read.
  365. This causes the initial value and any assigned values to be unused,
  366. allowing those expressions to be deleted if they have no side-effects.
  367.  
  368. Note that a let is actually a degenerate case of local call (?), and
  369. that let optimization can be done on calls that weren't created by a
  370. let.  Also, local call allows an applicative style of iteration that is
  371. totally assignment free.
  372.  
  373. 
  374. File: cmu-user.info  Node: Let Optimization-Footnotes, Up: Let Optimization
  375.  
  376. (7) The source transformation in this example doesn't represent the
  377. preservation of evaluation order implicit in the compiler's internal
  378. representation.  Where necessary, the back end will reintroduce
  379. temporaries to preserve the semantics.
  380.  
  381. 
  382. File: cmu-user.info  Node: Constant Folding, Prev: Let Optimization, Up: Source Optimization, Next: Unused Expression Elimination
  383.  
  384. Constant Folding
  385. ----------------
  386.  
  387.  
  388. Constant folding is an optimization that replaces a call of constant
  389. arguments with the constant result of that call.  Constant folding is
  390. done on all standard functions for which it is legal.  Inline expansion
  391. allows folding of any constant parts of the definition, and can be done
  392. even on functions that have side-effects.
  393.  
  394. It is convenient to rely on constant folding when programming, as in this
  395. example:
  396.      
  397.      (defconstant limit 42)
  398.      
  399.      (defun foo ()
  400.        (... (1- limit) ...))
  401.  
  402. Constant folding is also helpful when writing macros or inline
  403. functions, since it usually eliminates the need to write a macro that
  404. special-cases constant arguments.
  405.  
  406. Constant folding of a user defined function is enabled by the
  407. `extensions:constant-function' proclamation.   In this example:
  408.      
  409.      (declaim (ext:constant-function myfun))
  410.      (defun myexp (x y)
  411.        (declare (single-float x y))
  412.        (exp (* (log x) y)))
  413.      
  414.       ... (myexp 3.0 1.3) ...
  415.  
  416. The call to `myexp' is constant-folded to `4.1711674'.
  417.  
  418.  
  419. 
  420. File: cmu-user.info  Node: Unused Expression Elimination, Prev: Constant Folding, Up: Source Optimization, Next: Control Optimization
  421.  
  422. Unused Expression Elimination
  423. -----------------------------
  424.  
  425.  
  426. If the value of any expression is not used, and the expression has no
  427. side-effects, then it is deleted.  As with constant folding, this
  428. optimization applies most often when cleaning up after inline expansion
  429. and other optimizations.  Any function declared an
  430. `extensions:constant-function' is also subject to unused expression
  431. elimination.
  432.  
  433. Note that Python will eliminate parts of unused expressions known to be
  434. side-effect free, even if there are other unknown parts.  For example:
  435.      
  436.      (let ((a (list (foo) (bar))))
  437.        (if t
  438.            (zow)
  439.            (raz a)))
  440.  
  441. becomes:
  442.      
  443.      (progn (foo) (bar))
  444.      (zow)
  445.  
  446.  
  447.  
  448. 
  449. File: cmu-user.info  Node: Control Optimization, Prev: Unused Expression Elimination, Up: Source Optimization, Next: Unreachable Code Deletion
  450.  
  451. Control Optimization
  452. --------------------
  453.  
  454.  
  455. The most important optimization of control is recognizing when an if
  456. test is known at compile time, then deleting the `if', the test
  457. expression, and the unreachable branch of the `if'.  This can be
  458. considered a special case of constant folding, although the test doesn't
  459. have to be truly constant as long as it is definitely not false.  Note
  460. also, that type inference propagates the result of an `if' test to the
  461. true and false branches, *Note Dynamic Type Inference::.
  462.  
  463. A related `if' optimization is this transformation: (8) (*Note Control
  464. Optimization-Footnotes::)
  465.      
  466.      (if (if a b c) x y)
  467.  
  468. into:
  469.      
  470.      (if a
  471.          (if b x y)
  472.          (if c x y))
  473.  
  474. The opportunity for this sort of optimization usually results from a
  475. conditional macro.  For example:
  476.      
  477.      (if (not a) x y)
  478.  
  479. is actually implemented as this:
  480.      
  481.      (if (if a nil t) x y)
  482.  
  483. which is transformed to this:
  484.      
  485.      (if a
  486.          (if nil x y)
  487.          (if t x y))
  488.  
  489. which is then optimized to this:
  490.      
  491.      (if a y x)
  492.  
  493. Note that due to Python's internal representations, the `if'--`if'
  494. situation will be recognized even if other forms are wrapped around the inner
  495. `if', like:
  496.      
  497.      (if (let ((g ...))
  498.            (loop
  499.              ...
  500.              (return (not g))
  501.              ...))
  502.          x y)
  503.  
  504.  
  505. In Python, all the CMU Common Lisp macros really are macros, written in
  506. terms of `if', `block' and `tagbody', so user-defined control macros can
  507. be just as efficient as the standard ones.  Python emits basic blocks
  508. using a heuristic that minimizes the number of unconditional branches.
  509. The code in a `tagbody' will not be emitted in the order it appeared in
  510. the source, so there is no point in arranging the code to make control
  511. drop through to the target.
  512.  
  513. 
  514. File: cmu-user.info  Node: Control Optimization-Footnotes, Up: Control Optimization
  515.  
  516. (8) Note that the code for `x' and `y' isn't actually
  517. replicated.
  518.  
  519. 
  520. File: cmu-user.info  Node: Unreachable Code Deletion, Prev: Control Optimization, Up: Source Optimization, Next: Multiple Values Optimization
  521.  
  522. Unreachable Code Deletion
  523. -------------------------
  524.  
  525.  
  526. Python will delete code whenever it can prove that the code can never be
  527. executed.  Code becomes unreachable when:
  528.      
  529.    * An `if' is optimized away, or
  530.      
  531.    * There is an explicit unconditional control transfer such as `go' or
  532.      `return-from', or
  533.      
  534.    * The last reference to a local function is deleted (or there never was any
  535.      reference.)
  536.  
  537.  
  538.  
  539. When code that appeared in the original source is deleted, the compiler prints
  540. a note to indicate a possible problem (or at least unnecessary code.)  For
  541. example:
  542.      
  543.      (defun foo ()
  544.        (if t
  545.            (write-line "True.")
  546.            (write-line "False.")))
  547.  
  548. will result in this note:
  549.      
  550.      In: DEFUN FOO
  551.        (WRITE-LINE "False.")  Note: Deleting unreachable code.
  552.  
  553.  
  554. It is important to pay attention to unreachable code notes, since they often
  555. indicate a subtle type error.  For example:
  556.      
  557.      (defstruct foo a b)
  558.      
  559.      (defun lose (x)
  560.        (let ((a (foo-a x))
  561.              (b (if x (foo-b x) :none)))
  562.          ...))
  563.  
  564. results in this note:
  565.      
  566.      In: DEFUN LOSE
  567.        (IF X (FOO-B X) :NONE)
  568.      ==>
  569.        :NONE Note: Deleting unreachable code.
  570.  
  571. The :none is unreachable, because type inference knows that the argument
  572. to `foo-a' must be a `foo', and thus can't be false.  Presumably the
  573. programmer forgot that `x' could be false when he wrote the binding for
  574. `a'.
  575.  
  576. Here is an example with an incorrect declaration:
  577.      
  578.      (defun count-a (string)
  579.        (do ((pos 0 (position #\a string :start (1+ pos)))
  580.             (count 0 (1+ count)))
  581.            ((null pos) count)
  582.          (declare (fixnum pos))))
  583.  
  584. This time our note is:
  585.      
  586.      In: DEFUN COUNT-A
  587.        (DO ((POS 0 #) (COUNT 0 #))
  588.            ((NULL POS) COUNT)
  589.          (DECLARE (FIXNUM POS)))
  590.      --> BLOCK LET TAGBODY RETURN-FROM PROGN 
  591.      ==>
  592.        COUNT Note: Deleting unreachable code.
  593.  
  594. The problem here is that `pos' can never be null since it is declared a
  595. `fixnum'.
  596.  
  597. It takes some experience with unreachable code notes to be able to tell
  598. what they are trying to say.  In non-obvious cases, the best thing to do
  599. is to call the function in a way that should cause the unreachable code
  600. to be executed.  Either you will get a type error, or you will find that
  601. there truly is no way for the code to be executed.
  602.  
  603. Not all unreachable code results in a note:
  604.      
  605.    * A note is only given when the unreachable code textually appears in
  606.      the original source.  This prevents spurious notes due to the
  607.      optimization of macros and inline functions, but sometimes also
  608.      foregoes a note that would have been useful.
  609.      
  610.    * Since accurate source information is not available for non-list
  611.      forms, there is an element of heuristic in determining whether or
  612.      not to give a note about an atom.  Spurious notes may be given when
  613.      a macro or inline function defines a variable that is also present
  614.      in the calling function.  Notes about false and true are never
  615.      given, since it is too easy to confuse these constants in expanded
  616.      code with ones in the original source.
  617.      
  618.    * Notes are only given about code unreachable due to control flow.
  619.      There is no note when an expression is deleted because its value is
  620.      unused, since this is a common consequence of other optimizations.
  621.  
  622.  
  623.  
  624. Somewhat spurious unreachable code notes can also result when a macro inserts
  625. multiple copies of its arguments in different contexts, for example:
  626.      
  627.      (defmacro t-and-f (var form)
  628.        `(if ,var ,form ,form))
  629.      
  630.      (defun foo (x)
  631.        (t-and-f x (if x "True." "False.")))
  632.  
  633. results in these notes:
  634.      
  635.      In: DEFUN FOO
  636.        (IF X "True." "False.")
  637.      ==>
  638.        "False."  Note: Deleting unreachable code.
  639.      
  640.      ==>
  641.        "True."  Note: Deleting unreachable code.
  642.  
  643. It seems like it has deleted both branches of the `if', but it has
  644. really deleted one branch in one copy, and the other branch in the other
  645. copy.  Note that these messages are only spurious in not satisfying the
  646. intent of the rule that notes are only given when the deleted code
  647. appears in the original source; there is always SOME code being deleted
  648. when a unreachable code note is printed.
  649.  
  650.  
  651. 
  652. File: cmu-user.info  Node: Multiple Values Optimization, Prev: Unreachable Code Deletion, Up: Source Optimization, Next: Source to Source Transformation
  653.  
  654. Multiple Values Optimization
  655. ----------------------------
  656.  
  657.  
  658. Within a function, Python implements uses of multiple values particularly
  659. efficiently.  Multiple values can be kept in arbitrary registers, so using
  660. multiple values doesn't imply stack manipulation and representation
  661. conversion.  For example, this code:
  662.      
  663.      (let ((a (if x (foo x) u))
  664.            (b (if x (bar x) v)))
  665.        ...)
  666.  
  667. is actually more efficient written this way:
  668.      
  669.      (multiple-value-bind
  670.          (a b)
  671.          (if x
  672.              (values (foo x) (bar x))
  673.              (values u v))
  674.        ...)
  675.  
  676.  
  677. Also, ? for information on how local call provides efficient support for
  678. multiple function return values.
  679.  
  680.  
  681. 
  682. File: cmu-user.info  Node: Source to Source Transformation, Prev: Multiple Values Optimization, Up: Source Optimization, Next: Style Recommendations
  683.  
  684. Source to Source Transformation
  685. -------------------------------
  686.  
  687.  
  688. The compiler implements a number of operation-specific optimizations as
  689. source-to-source transformations.  You will often see unfamiliar code in error
  690. messages, for example:
  691.      
  692.      (defun my-zerop () (zerop x))
  693.  
  694. gives this warning:
  695.      
  696.      In: DEFUN MY-ZEROP
  697.        (ZEROP X)
  698.      ==>
  699.        (= X 0)
  700.      Warning: Undefined variable: X
  701.  
  702. The original `zerop' has been transformed into a call to `='.  This
  703. transformation is indicated with the same `==>' used to mark macro and
  704. function inline expansion.  Although it can be confusing, display of the
  705. transformed source is important, since warnings are given with respect to the
  706. transformed source.  This a more obscure example:
  707.      
  708.      (defun foo (x) (logand 1 x))
  709.  
  710. gives this efficiency note:
  711.      
  712.      In: DEFUN FOO
  713.        (LOGAND 1 X)
  714.      ==>
  715.        (LOGAND C::Y C::X)
  716.      Note: Forced to do static-function Two-arg-and (cost 53).
  717.            Unable to do inline fixnum arithmetic (cost 1) because:
  718.            The first argument is a INTEGER, not a FIXNUM.
  719.            etc.
  720.  
  721. Here, the compiler commuted the call to `logand', introducing
  722. temporaries.  The note complains that the FIRST argument is not a
  723. `fixnum', when in the original call, it was the second argument.  To
  724. make things more confusing, the compiler introduced temporaries called
  725. `c::x' and `c::y' that are bound to `y' and `1', respectively.
  726.  
  727. You will also notice source-to-source optimizations when efficiency notes are
  728. enabled (?.)  When the compiler is unable to
  729. do a transformation that might be possible if there was more information, then
  730. an efficiency note is printed.  For example, `my-zerop' above will also give
  731. this efficiency note:
  732.      
  733.      In: DEFUN FOO
  734.        (ZEROP X)
  735.      ==>
  736.        (= X 0)
  737.      Note: Unable to optimize because:
  738.            Operands might not be the same type, so can't open code.
  739.  
  740.  
  741. 
  742. File: cmu-user.info  Node: Style Recommendations, Prev: Source to Source Transformation, Up: Source Optimization
  743.  
  744. Style Recommendations
  745. ---------------------
  746.  
  747.  
  748. Source level optimization makes possible a clearer and more relaxed programming
  749. style:
  750.      
  751.    * Don't use macros purely to avoid function call.  If you want an
  752.      inline function, write it as a function and declare it inline.
  753.      It's clearer, less error-prone, and works just as well.
  754.      
  755.    * Don't write macros that try to "optimize" their expansion in
  756.      trivial ways such as avoiding binding variables for simple
  757.      expressions.  The compiler does these optimizations too, and is
  758.      less likely to make a mistake.
  759.      
  760.    * Make use of local functions (i.e., `labels' or `flet') and
  761.      tail-recursion in places where it is clearer.  Local function call
  762.      is faster than full call.
  763.      
  764.    * Avoid setting local variables when possible.  Binding a new `let'
  765.      variable is at least as efficient as setting an existing variable,
  766.      and is easier to understand, both for the compiler and the
  767.      programmer.
  768.      
  769.    * Instead of writing similar code over and over again so that it can
  770.      be hand customized for each use, define a macro or inline function,
  771.      and let the compiler do the work.
  772.  
  773.  
  774.  
  775.  
  776. 
  777. File: cmu-user.info  Node: Tail Recursion, Prev: Source Optimization, Up: Advanced Compiler Use and Efficiency Hints, Next: Local Call
  778.  
  779. Tail Recursion
  780. ==============
  781.  
  782.  
  783. A call is tail-recursive if nothing has to be done after the the call returns,
  784. i.e. when the call returns, the returned value is immediately returned from the
  785. calling function.  In this example, the recursive call to `myfun' is
  786. tail-recursive:
  787.      
  788.      (defun myfun (x)
  789.        (if (oddp (random x))
  790.            (isqrt x)
  791.            (myfun (1- x))))
  792.  
  793.  
  794. Tail recursion is interesting because it is form of recursion that can
  795. be implemented much more efficiently than general recursion.  In
  796. general, a recursive call requires the compiler to allocate storage on
  797. the stack at run-time for every call that has not yet returned.  This
  798. memory consumption makes recursion unacceptably inefficient for
  799. representing repetitive algorithms having large or unbounded size.  Tail
  800. recursion is the special case of recursion that is semantically
  801. equivalent to the iteration constructs normally used to represent
  802. repetition in programs.  Because tail recursion is equivalent to
  803. iteration, tail-recursive programs can be compiled as efficiently as
  804. iterative programs.
  805.  
  806. So why would you want to write a program recursively when you can write it
  807. using a loop?  Well, the main answer is that recursion is a more general
  808. mechanism, so it can express some solutions simply that are awkward to write as
  809. a loop.  Some programmers also feel that recursion is a stylistically
  810. preferable way to write loops because it avoids assigning variables.
  811. For example, instead of writing:
  812.      
  813.      (defun fun1 (x)
  814.        something-that-uses-x)
  815.      
  816.      (defun fun2 (y)
  817.        something-that-uses-y)
  818.      
  819.      (do ((x something (fun2 (fun1 x))))
  820.          (nil))
  821.  
  822. You can write:
  823.      
  824.      (defun fun1 (x)
  825.        (fun2 something-that-uses-x))
  826.      
  827.      (defun fun2 (y)
  828.        (fun1 something-that-uses-y))
  829.      
  830.      (fun1 something)
  831.  
  832. The tail-recursive definition is actually more efficient, in addition to
  833. being (arguably) clearer.  As the number of functions and the complexity
  834. of their call graph increases, the simplicity of using recursion becomes
  835. compelling.  Consider the advantages of writing a large finite-state
  836. machine with separate tail-recursive functions instead of using a single
  837. huge `prog'.
  838.  
  839. It helps to understand how to use tail recursion if you think of a
  840. tail-recursive call as a `psetq' that assigns the argument values to the
  841. called function's variables, followed by a `go' to the start of the called
  842. function.  This makes clear an inherent efficiency advantage of tail-recursive
  843. call: in addition to not having to allocate a stack frame, there is no need to
  844. prepare for the call to return (e.g., by computing a return PC.)
  845.  
  846. Is there any disadvantage to tail recursion?  Other than an increase in
  847. efficiency, the only way you can tell that a call has been compiled
  848. tail-recursively is if you use the debugger.  Since a tail-recursive
  849. call has no stack frame, there is no way the debugger can print out the
  850. stack frame representing the call.  The effect is that backtrace will
  851. not show some calls that would have been displayed in a
  852. non-tail-recursive implementation.  In practice, this is not as bad as
  853. it sounds -- in fact it isn't really clearly worse, just different.
  854. *Note Debug Tail Recursion:: for information about the debugger
  855. implications of tail recursion.
  856.  
  857. In order to ensure that tail-recursion is preserved in arbitrarily complex
  858. calling patterns across separately compiled functions, the compiler must
  859. compile any call in a tail-recursive position as a tail-recursive call.  This
  860. is done regardless of whether the program actually exhibits any sort of
  861. recursive calling pattern.  In this example, the call to `fun2' will always
  862. be compiled as a tail-recursive call:
  863.      
  864.      (defun fun1 (x)
  865.        (fun2 x))
  866.  
  867. So tail recursion doesn't necessarily have anything to do with recursion
  868. as it is normally thought of.  ? for more discussion of using tail
  869. recursion to implement loops.
  870.  
  871. * Menu:
  872.  
  873. * Tail Recursion Exceptions::   
  874.  
  875.  
  876. 
  877. File: cmu-user.info  Node: Tail Recursion Exceptions, Prev: Tail Recursion, Up: Tail Recursion
  878.  
  879. Tail Recursion Exceptions
  880. -------------------------
  881.  
  882.  
  883. Although Python is claimed to be "properly" tail-recursive, some might dispute
  884. this, since there are situations where tail recursion is inhibited:
  885.      
  886.    * When the call is enclosed by a special binding, or
  887.      
  888.    * When the call is enclosed by a `catch' or `unwind-protect', or
  889.      
  890.    * When the call is enclosed by a `block' or `tagbody' and the block
  891.      name or `go' tag has been closed over.
  892.  
  893. These dynamic extent binding forms inhibit tail recursion because they
  894. allocate stack space to represent the binding.  Shallow-binding
  895. implementations of dynamic scoping also require cleanup code to be
  896. evaluated when the scope is exited.
  897.  
  898.  
  899. 
  900. File: cmu-user.info  Node: Local Call, Prev: Tail Recursion, Up: Advanced Compiler Use and Efficiency Hints, Next: Block Compilation
  901.  
  902. Local Call
  903. ==========
  904.  
  905.  
  906. Python supports two kinds of function call: full call and local call.  Full
  907. call is the standard calling convention; its late binding and generality make
  908. Common Lisp what it is, but create unavoidable overheads.  When the compiler can
  909. compile the calling function and the called function simultaneously, it can use
  910. local call to avoid some of the overhead of full call.  Local call is really a
  911. collection of compilation strategies.  If some aspect of call overhead is not
  912. needed in a particular local call, then it can be omitted.  In some cases,
  913. local call can be totally free.  Local call provides two main advantages to the
  914. user:
  915.      
  916.    * Local call makes the use of the lexical function binding forms flet
  917.      and labels much more efficient.  A local call is always faster than
  918.      a full call, and in many cases is much faster.
  919.      
  920.    * Local call is a natural approach to block compilation, a
  921.      compilation technique that resolves function references at compile
  922.      time.  Block compilation speeds function call, but increases
  923.      compilation times and prevents function redefinition.
  924.  
  925.  
  926.  
  927. * Menu:
  928.  
  929. * Self-Recursive Calls::        
  930. * Let Calls::                   
  931. * Closures::                    
  932. * Local Tail Recursion::        
  933. * Return Values::               
  934.  
  935.  
  936. 
  937. File: cmu-user.info  Node: Self-Recursive Calls, Prev: Local Call, Up: Local Call, Next: Let Calls
  938.  
  939. Self-Recursive Calls
  940. --------------------
  941.  
  942.  
  943. Local call is used when a function defined by `defun' calls itself.  For
  944. example:
  945.      
  946.      (defun fact (n)
  947.        (if (zerop n)
  948.            1
  949.            (* n (fact (1- n)))))
  950.  
  951. This use of local call speeds recursion, but can also complicate debugging,
  952. since trace will only show the first call to `fact', and not the
  953. recursive calls.  This is because the recursive calls directly jump to the
  954. start of the function, and don't indirect through the `symbol-function'.
  955. Self-recursive local call is inhibited when the :block-compile argument to
  956. `compile-file' is false (?.)
  957.  
  958. 
  959. File: cmu-user.info  Node: Let Calls, Prev: Self-Recursive Calls, Up: Local Call, Next: Closures
  960.  
  961. Let Calls
  962. ---------
  963.  
  964. Because local call avoids unnecessary call overheads, the compiler internally
  965. uses local call to implement some macros and special forms that are not
  966. normally thought of as involving a function call.  For example, this `let':
  967.      
  968.      (let ((a (foo))
  969.            (b (bar)))
  970.        ...)
  971.  
  972. is internally represented as though it was macroexpanded into:
  973.      
  974.      (funcall #'(lambda (a b)
  975.                   ...)
  976.               (foo)
  977.               (bar))
  978.  
  979. This implementation is acceptable because the simple cases of local call
  980. (equivalent to a `let') result in good code.  This doesn't make `let' any
  981. more efficient, but does make local calls that are semantically the same as `let'
  982. much more efficient than full calls.  For example, these definitions are all
  983. the same as far as the compiler is concerned:
  984.      
  985.      (defun foo ()
  986.        ...some other stuff...
  987.        (let ((a something))
  988.          ...some stuff...))
  989.      
  990.      (defun foo ()
  991.        (flet ((localfun (a)
  992.                 ...some stuff...))
  993.          ...some other stuff...
  994.          (localfun something)))
  995.      
  996.      (defun foo ()
  997.        (let ((funvar #'(lambda (a)
  998.                          ...some stuff...)))
  999.          ...some other stuff...
  1000.          (funcall funvar something)))
  1001.  
  1002.  
  1003. Although local call is most efficient when the function is called only
  1004. once, a call doesn't have to be equivalent to a `let' to be more
  1005. efficient than full call.  All local calls avoid the overhead of
  1006. argument count checking and keyword argument parsing, and there are a
  1007. number of other advantages that apply in many common situations.  *Note
  1008. Let Optimization:: for a discussion of the optimizations done on let
  1009. calls.
  1010.  
  1011. 
  1012. File: cmu-user.info  Node: Closures, Prev: Let Calls, Up: Local Call, Next: Local Tail Recursion
  1013.  
  1014. Closures
  1015. --------
  1016.  
  1017.  
  1018. Local call allows for much more efficient use of closures, since the closure
  1019. environment doesn't need to be allocated on the heap, or even stored in memory
  1020. at all.  In this example, there is no penalty for `localfun' referencing
  1021. `a' and `b':
  1022.      
  1023.      (defun foo (a b)
  1024.        (flet ((localfun (x)
  1025.                 (1+ (* a b x))))
  1026.          (if (= a b)
  1027.              (localfun (- x))
  1028.              (localfun x))))
  1029.  
  1030. In local call, the compiler effectively passes closed-over values as extra
  1031. arguments, so there is no need for you to "optimize" local function use by
  1032. explicitly passing in lexically visible values.  Closures may also be subject
  1033. to let optimization (*Note Let Optimization::.)
  1034.  
  1035. Note: indirect value cells are currently always allocated on the heap
  1036. when a variable is both assigned to (with `setq' or `setf') and closed
  1037. over, regardless of whether the closure is a local function or not.
  1038. This is another reason to avoid setting variables when you don't have
  1039. to.
  1040.  
  1041. 
  1042. File: cmu-user.info  Node: Local Tail Recursion, Prev: Closures, Up: Local Call, Next: Return Values
  1043.  
  1044. Local Tail Recursion
  1045. --------------------
  1046.  
  1047.  
  1048. Tail-recursive local calls are particularly efficient, since they are in effect
  1049. an assignment plus a control transfer.  Scheme programmers write loops with
  1050. tail-recursive local calls, instead of using the imperative `go' and
  1051. `setq'.  This has not caught on in the CMU Common Lisp community, since conventional
  1052. Common Lisp compilers don't implement local call.  In Python, users can choose to
  1053. write loops such as:
  1054.      
  1055.      (defun ! (n)
  1056.        (labels ((loop (n total)
  1057.                   (if (zerop n)
  1058.                       total
  1059.                       (loop (1- n) (* n total)))))
  1060.          (loop n 1)))
  1061.  
  1062.  
  1063.  
  1064.  -- Macro: iterate NAME ({(VAR INITIAL-VALUE)}*) {DECLARATION}* {FORM}*
  1065.  
  1066.      This macro provides syntactic sugar for using labels to do
  1067.      iteration.  It creates a local function NAME with the specified
  1068.      VARs as its arguments and the DECLARATIONs and FORMs as its body.
  1069.      This function is then called with the INITIAL-VALUES, and the
  1070.      result of the call is return from the macro.
  1071.      
  1072.      Here is our factorial example rewritten using `iterate':
  1073.           
  1074.           (defun ! (n)
  1075.             (iterate loop
  1076.                      ((n n)
  1077.                       (total 1))
  1078.               (if (zerop n)
  1079.                   total
  1080.                   (loop (1- n) (* n total)))))
  1081.      
  1082.      The main advantage of using `iterate' over `do' is that `iterate'
  1083.      naturally allows stepping to be done differently depending on conditionals in
  1084.      the body of the loop.  `iterate' can also be used to implement algorithms
  1085.      that aren't really iterative by simply doing a non-tail call.  For example,
  1086.      the standard recursive definition of factorial can be written like this:
  1087.           
  1088.           (iterate fact
  1089.                    ((n n))
  1090.             (if (zerop n)
  1091.                 1
  1092.                 (* n (fact (1- n)))))
  1093.      
  1094.  
  1095.  
  1096. 
  1097. File: cmu-user.info  Node: Return Values, Prev: Local Tail Recursion, Up: Local Call
  1098.  
  1099. Return Values
  1100. -------------
  1101.  
  1102.  
  1103. One of the more subtle costs of full call comes from allowing arbitrary
  1104. numbers of return values.  This overhead can be avoided in local calls
  1105. to functions that always return the same number of values.  For
  1106. efficiency reasons (as well as stylistic ones), you should write
  1107. functions so that they always return the same number of values.  This
  1108. may require passing extra false arguments to `values' in some cases, but
  1109. the result is more efficient, not less so.
  1110.  
  1111. When efficiency notes are enabled (?), and the
  1112. compiler wants to use known values return, but can't prove that the function
  1113. always returns the same number of values, then it will print a note like this:
  1114.      
  1115.      In: DEFUN GRUE
  1116.        (DEFUN GRUE (X) (DECLARE (FIXNUM X)) (COND (# #) (# NIL) (T #)))
  1117.      Note: Return type not fixed values, so can't use known return convention:
  1118.        (VALUES (OR (INTEGER -536870912 -1) NULL) &REST T)
  1119.  
  1120.  
  1121. In order to implement proper tail recursion in the presence of known values
  1122. return (*Note Tail Recursion::), the compiler sometimes must prove that
  1123. multiple functions all return the same number of values.  When this can't be
  1124. proven, the compiler will print a note like this:
  1125.      
  1126.      In: DEFUN BLUE
  1127.        (DEFUN BLUE (X) (DECLARE (FIXNUM X)) (COND (# #) (# #) (# #) (T #)))
  1128.      Note: Return value count mismatch prevents known return from
  1129.            these functions:
  1130.        BLUE
  1131.        SNOO
  1132.  
  1133. ? for the interaction between local call and the representation of
  1134. numeric types.
  1135.  
  1136.  
  1137. 
  1138. File: cmu-user.info  Node: Block Compilation, Prev: Local Call, Up: Advanced Compiler Use and Efficiency Hints, Next: Inline Expansion
  1139.  
  1140. Block Compilation
  1141. =================
  1142.  
  1143.  
  1144. Block compilation allows calls to global functions defined by defun to
  1145. be compiled as local calls.  The function call can be in a different
  1146. top-level form than the `defun', or even in a different file.
  1147.  
  1148. In addition, block compilation allows the declaration of the entry
  1149. points to the block compiled portion.  An entry point is any function
  1150. that may be called from outside of the block compilation.  If a function
  1151. is not an entry point, then it can be compiled more efficiently, since
  1152. all calls are known at compile time.  In particular, if a function is
  1153. only called in one place, then it will be let converted.  This
  1154. effectively inline expands the function, but without the code
  1155. duplication that results from defining the function normally and then
  1156. declaring it inline.
  1157.  
  1158. The main advantage of block compilation is that it it preserves efficiency in
  1159. programs even when (for readability and syntactic convenience) they are broken
  1160. up into many small functions.  There is absolutely no overhead for calling a
  1161. non-entry point function that is defined purely for modularity (i.e. called
  1162. only in one place.)
  1163.  
  1164. Block compilation also allows the use of non-descriptor arguments and
  1165. return values in non-trivial programs (?).
  1166.  
  1167. * Menu:
  1168.  
  1169. * Block Compilation Semantics::  
  1170. * Block Compilation Declarations::  
  1171. * Compiler Arguments::          
  1172. * Practical Difficulties::      
  1173.  
  1174.  
  1175. 
  1176. File: cmu-user.info  Node: Block Compilation Semantics, Prev: Block Compilation, Up: Block Compilation, Next: Block Compilation Declarations
  1177.  
  1178. Block Compilation Semantics
  1179. ---------------------------
  1180.  
  1181.  
  1182. The effect of block compilation can be envisioned as the compiler turning all
  1183. the `defun's in the block compilation into a single `labels' form:
  1184.      
  1185.      (declaim (start-block fun1 fun3))
  1186.      
  1187.      (defun fun1 ()
  1188.        ...)
  1189.      
  1190.      (defun fun2 ()
  1191.        ...
  1192.        (fun1)
  1193.        ...)
  1194.      
  1195.      (defun fun3 (x)
  1196.        (if x
  1197.            (fun1)
  1198.            (fun2)))
  1199.      
  1200.      (declaim (end-block))
  1201.  
  1202. becomes:
  1203.      
  1204.      (labels ((fun1 ()
  1205.                 ...)
  1206.               (fun2 ()
  1207.                 ...
  1208.                 (fun1)
  1209.                 ...)
  1210.               (fun3 (x)
  1211.                 (if x
  1212.                     (fun1)
  1213.                     (fun2))))
  1214.        (setf (fdefinition 'fun1) #'fun1)
  1215.        (setf (fdefinition 'fun3) #'fun3))
  1216.  
  1217. Calls between the block compiled functions are local calls, so changing
  1218. the global definition of `fun1' will have no effect on what `fun2' does;
  1219. `fun2' will keep calling the old `fun1'.
  1220.  
  1221. The entry points `fun1' and `fun3' are still installed in the
  1222. `symbol-function' as the global definitions of the functions, so a full
  1223. call to an entry point works just as before.  However, `fun2' is not an
  1224. entry point, so it is not globally defined.  In addition, `fun2' is only
  1225. called in one place, so it will be let converted.
  1226.  
  1227.  
  1228. 
  1229. File: cmu-user.info  Node: Block Compilation Declarations, Prev: Block Compilation Semantics, Up: Block Compilation, Next: Compiler Arguments
  1230.  
  1231. Block Compilation Declarations
  1232. ------------------------------
  1233.  
  1234.  
  1235. The `extensions:start-block' and `extensions:end-block' declarations
  1236. allow fine-grained control of block compilation.  These declarations are
  1237. only legal as a global declarations (`declaim' or `proclaim').
  1238.  
  1239. The `start-block' declaration has this syntax:
  1240.      
  1241.      (start-block {ENTRY-POINT-NAME}*)
  1242.  
  1243. When processed by the compiler, this declaration marks the start of
  1244. block compilation, and specifies the entry points to that block.  If no
  1245. entry points are specified, then ALL functions are made into entry
  1246. points.  If already block compiling, then the compiler ends the current
  1247. block and starts a new one.
  1248.  
  1249. The `end-block' declaration has no arguments:
  1250.      
  1251.      (end-block)
  1252.  
  1253. The `end-block' declaration ends a block compilation unit without
  1254. starting a new one.  This is useful mainly when only a portion of a file
  1255. is worth block compiling.
  1256.  
  1257. 
  1258. File: cmu-user.info  Node: Compiler Arguments, Prev: Block Compilation Declarations, Up: Block Compilation, Next: Practical Difficulties
  1259.  
  1260. Compiler Arguments
  1261. ------------------
  1262.  
  1263.  
  1264. The :block-compile and :entry-points arguments to
  1265. `extensions:compile-from-stream' and compile-file *Note Calling the
  1266. Compiler:: provide overall control of block compilation, and allow block
  1267. compilation without requiring modification of the program source.
  1268.  
  1269. There are three possible values of the :block-compile argument:
  1270.      
  1271. false     
  1272.      
  1273.      Do no compile-time resolution of global function names, not even
  1274.      for self-recursive calls.  This inhibits any `start-block'
  1275.      declarations appearing in the file, allowing all functions to be
  1276.      incrementally redefined.
  1277.      
  1278. true     
  1279.      
  1280.      Start compiling in block compilation mode.  This is mainly useful
  1281.      for block compiling small files that contain no `start-block'
  1282.      declarations.  See also the :entry-points argument.
  1283.      
  1284. :specified     
  1285.      
  1286.      Start compiling in form-at-a-time mode, but exploit `start-block'
  1287.      declarations and compile self-recursive calls as local calls.  Normally
  1288.      :specified is the default for this argument (see
  1289.      block-compile-default ?.)
  1290.  
  1291.  
  1292. The :entry-points argument can be used in conjunction with
  1293. :block-compile true to specify the entry-points to a block-compiled
  1294. file.  If not specified or nil, all global functions will be compiled as
  1295. entry points.  When :block-compile is not true, this argument is
  1296. ignored.
  1297.  
  1298.  
  1299.  
  1300.  -- Variable: *block-compile-default*
  1301.      This variable determines the default value for the :block-compile
  1302.      argument to `compile-file' and `compile-from-stream'.  The initial
  1303.      value of this variable is :specified, but false is sometimes useful
  1304.      for totally inhibiting block compilation.
  1305.  
  1306.  
  1307. 
  1308. File: cmu-user.info  Node: Practical Difficulties, Prev: Compiler Arguments, Up: Block Compilation
  1309.  
  1310. Practical Difficulties
  1311. ----------------------
  1312.  
  1313.  
  1314. The main problem with block compilation is that the compiler uses large
  1315. amounts of memory when it is block compiling.  This places an upper
  1316. limit on the amount of code that can be block compiled as a unit.  To
  1317. make best use of block compilation, it is necessary to locate the parts
  1318. of the program containing many internal calls, and then add the
  1319. appropriate `start-block' declarations.  When writing new code, it is a
  1320. good idea to put in block compilation declarations from the very
  1321. beginning, since writing block declarations correctly requires accurate
  1322. knowledge of the program's function call structure.  If you want to
  1323. initially develop code with full incremental redefinition, you can
  1324. compile with block-compile-default *Note Compiler Arguments:: set to
  1325. false.
  1326.  
  1327. Note if a `defun' appears in a non-null lexical environment, then calls
  1328. to it cannot be block compiled.
  1329.  
  1330. Unless files are very small, it is probably impractical to block compile
  1331. multiple files as a unit by specifying a list of files to
  1332. `compile-file'.  Semi-inline expansion (?) provides another way to
  1333. extend block compilation across file boundaries.
  1334.  
  1335.  
  1336. 
  1337. File: cmu-user.info  Node: Inline Expansion, Prev: Block Compilation, Up: Advanced Compiler Use and Efficiency Hints, Next: Object Representation
  1338.  
  1339. Inline Expansion
  1340. ================
  1341.  
  1342.  
  1343. Python can expand almost any function inline, including functions with
  1344. keyword arguments.  The only restrictions are that keyword argument
  1345. keywords in the call must be constant, and that global function
  1346. definitions (`defun') must be done in a null lexical environment (not
  1347. nested in a `let' or other binding form.)  Local functions (`flet') can
  1348. be inline expanded in any environment.  Combined with Python's
  1349. source-level optimization, inline expansion can be used for things that
  1350. formerly required macros for efficient implementation.  In Python,
  1351. macros don't have any efficiency advantage, so they need only be used
  1352. where a macro's syntactic flexibility is required.
  1353.  
  1354. Inline expansion is a compiler optimization technique that reduces
  1355. the overhead of a function call by simply not doing the call:
  1356. instead, the compiler effectively rewrites the program to appear as
  1357. though the definition of the called function was inserted at each
  1358. call site.  In Common Lisp, this is straightforwardly expressed by
  1359. inserting the `lambda' corresponding to the original definition:
  1360.      
  1361.      (proclaim '(inline my-1+))
  1362.      (defun my-1+ (x) (+ x 1))
  1363.      
  1364.      (my-1+ someval) =>  ((lambda (x) (+ x 1)) someval)
  1365.  
  1366.  
  1367. When the function expanded inline is large, the program after inline expansion
  1368. may be substantially larger than the original program.  If the program becomes
  1369. too large, inline expansion hurts speed rather than helping it, since hardware
  1370. resources such as physical memory and cache will be exhausted.  Inline
  1371. expansion is called for:
  1372.      
  1373.    * When profiling has shown that a relatively simple function is
  1374.      called so often that a large amount of time is being wasted in the
  1375.      calling of that function (as opposed to running in that function.)
  1376.      If a function is complex, it will take a long time to run relative
  1377.      the time spent in call, so the speed advantage of inline expansion
  1378.      is diminished at the same time the space cost of inline expansion
  1379.      is increased.  Of course, if a function is rarely called, then the
  1380.      overhead of calling it is also insignificant.
  1381.      
  1382.    * With functions so simple that they take less space to inline expand
  1383.      than would be taken to call the function (such as `my-1+' above.)
  1384.      It would require intimate knowledge of the compiler to be certain
  1385.      when inline expansion would reduce space, but it is generally safe
  1386.      to inline expand functions whose definition is a single function
  1387.      call, or a few calls to simple CMU Common Lisp functions.
  1388.  
  1389.  
  1390.  
  1391. In addition to this speed/space tradeoff from inline expansion's
  1392. avoidance of the call, inline expansion can also reveal opportunities
  1393. for optimization.  Python's extensive source-level optimization can make
  1394. use of context information from the caller to tremendously simplify the
  1395. code resulting from the inline expansion of a function.
  1396.  
  1397. The main form of caller context is local information about the actual
  1398. argument values: what the argument types are and whether the arguments
  1399. are constant.  Knowledge about argument types can eliminate run-time
  1400. type tests (e.g., for generic arithmetic.)  Constant arguments in a call
  1401. provide opportunities for constant folding optimization after inline
  1402. expansion.
  1403.  
  1404. A hidden way that constant arguments are often supplied to functions is through
  1405. the defaulting of unsupplied optional or keyword arguments.  There can be a
  1406. huge efficiency advantage to inline expanding functions that have complex
  1407. keyword-based interfaces, such as this definition of the `member' function:
  1408.      
  1409.      (proclaim '(inline member))
  1410.      (defun member (item list &key
  1411.                          (key #'identity)
  1412.                          (test #'eql testp)
  1413.                          (test-not nil notp))
  1414.        (do ((list list (cdr list)))
  1415.            ((null list) nil)
  1416.          (let ((car (car list)))
  1417.            (if (cond (testp
  1418.                       (funcall test item (funcall key car)))
  1419.                      (notp
  1420.                       (not (funcall test-not item (funcall key car))))
  1421.                      (t
  1422.                       (funcall test item (funcall key car))))
  1423.                (return list)))))
  1424.      
  1425.  
  1426. After inline expansion, this call is simplified to the obvious code:
  1427.      
  1428.      (member a l :key #'foo-a :test #'char=) => 
  1429.      
  1430.      (do ((list list (cdr list)))
  1431.          ((null list) nil)
  1432.        (let ((car (car list)))
  1433.          (if (char= item (foo-a car))
  1434.              (return list))))
  1435.  
  1436. In this example, there could easily be more than an order of magnitude
  1437. improvement in speed.  In addition to eliminating the original call to
  1438. `member', inline expansion also allows the calls to `char=' and `foo-a'
  1439. to be open-coded.  We go from a loop with three tests and two calls to a
  1440. loop with one test and no calls.
  1441.  
  1442. *Note Source Optimization:: for more discussion of source level
  1443. optimization.
  1444.  
  1445. * Menu:
  1446.  
  1447. * Inline Expansion Recording::  
  1448. * Semi-Inline Expansion::       
  1449. * The Maybe-Inline Declaration::  
  1450.  
  1451.  
  1452. 
  1453.